package org.netty.mvc.tool;

import java.util.HashMap;
import java.util.Map;

public class URLTool {
    public static String parseUrlKey(String urlStr) {
        String[] urlStrArr = urlStr.split("\\?");
        StringBuilder params = new StringBuilder();
        StringBuilder urlKey = new StringBuilder(urlStrArr[0].substring(1));
        String query = urlStr.substring(urlKey.length() + 1);
        if (!"".equals(query)) {
            String[] paramArr = query.substring(1).split("&");
            for (int i = 0; i < paramArr.length; i++) {
                String param = paramArr[i].split("=")[0];
                if (i == paramArr.length - 1) {
                    params.append(param);
                } else {
                    params.append(param).append("&");
                }
            }
        }
        if (!"".equals(params.toString())) {
            urlKey.append("?").append(params);
        }
        return urlKey.toString();
    }

    public static Map<String, String> parseQuery(String queryStr) {
        Map<String, String> queryMap = new HashMap<>();
        String[] queryKV = queryStr.split("&");
        for (String kv : queryKV) {
            String[] v = kv.split("=");
            queryMap.put(v[0], v[1]);
        }
        return queryMap;
    }
}
